﻿using System;
using System.Linq;
using System.Web.Mvc;
using BLL;
using Model;

namespace Web.Areas.Manager.Controllers
{
    [NoCache]
    [HandleError]
    [UserAuthorize]
    public partial class Sys_RolesController : Controller
    {
        Sys_Roles_BLL _Sys_Roles_BLL = new Sys_Roles_BLL();
        Sys_Actions_BLL _Sys_Actions_BLL = new Sys_Actions_BLL();
        Sys_Controllers_BLL _Sys_Controllers_BLL = new Sys_Controllers_BLL();
        Sys_ActionsInControllersInRoles_BLL _Sys_ActionsInControllersInRoles_BLL = new Sys_ActionsInControllersInRoles_BLL();

        public virtual ActionResult Index(int? pageIndex, string keyword)
        {
            var model = _Sys_Roles_BLL.Get();
            if (!string.IsNullOrEmpty(keyword))
            {
                model = model.Where(a => a.RoleName.Contains(keyword));
            }
            return View(model.ToPagedList(pageIndex));
        }

        public virtual ActionResult Edit(Guid? id)
        {
            ViewData.Add("Sys_Actions", _Sys_Actions_BLL.Get());
            ViewData.Add("Sys_Controllers", _Sys_Controllers_BLL.Get().Where(a => a.Enable));

            var item = _Sys_Roles_BLL.Get(id);
            return View(item);
        }

        [HttpPost]
        public virtual ActionResult Edit(Guid? id, Sys_Roles collection)
        {
            Edit(id);

            if (!ModelState.IsValid)
            {
                return View();
            }

            _Sys_Roles_BLL.Save(id, ref collection);

            foreach (var sys_controller in _Sys_Controllers_BLL.Get())
            {
                foreach (var sys_action in _Sys_Actions_BLL.Get())
                {
                    _Sys_ActionsInControllersInRoles_BLL.Delete(sys_action.Id, sys_controller.Id, collection.Id);
                    if (Request[sys_controller.Id.ToString() + sys_action.Id.ToString()] != "false")
                    {
                        _Sys_ActionsInControllersInRoles_BLL.Insert(sys_action.Id, sys_controller.Id, collection.Id);
                    }
                }
            }

            return RedirectToAction("Index");

        }

        [HttpDelete]
        public virtual ActionResult Delete(Guid Id)
        {
            _Sys_Roles_BLL.DeleteObject(Id);
            return RedirectToAction("Index");
        }
    }
}
